package com.bjpowernode.controller;

import cn.hutool.core.util.StrUtil;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.entity.query.UserQuery;
import com.bjpowernode.common.result.Result;
import com.bjpowernode.service.UserService;
import com.bjpowernode.util.LoginInfoUtil;
import com.bjpowernode.entity.vo.OwnerVO;
import com.github.pagehelper.PageInfo;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("api/login/user")
    public Result loginUser() {
        //从security中获取登录的用户信息
        TUser currentLoginUser = LoginInfoUtil.getCurrentLoginUser();

        //将登录的用户信息返回给前端
        return Result.OK(currentLoginUser);
    }

    @GetMapping("/api/users")
    public Result users(@RequestParam(value = "current") Integer current) {
        PageInfo<TUser> pageInfo = userService.getUserByPage(current);
        return Result.OK(pageInfo);
    }

    @GetMapping("/api/user/{id}")
    public Result user(@PathVariable(value = "id") Integer id) {
        TUser user = userService.getUserById(id);
        return Result.OK(user);
    }

    @PostMapping("api/user")
    public Result addUser(@Valid UserQuery userQuery) {
        int flag = userService.addUser(userQuery);
        if (flag > 0) {
            return Result.OK();
        }else {
            return Result.FAIL();
        }
    }

    @PutMapping("/api/user")
    public Result updateUser(UserQuery userQuery) {
        int flag = userService.updateUser(userQuery);
        if (flag > 0) {
            return Result.OK();
        }else {
            return Result.FAIL();
        }
    }

    @DeleteMapping("/api/user/{id}")
    public Result deleteUser(@PathVariable(value = "id") Integer id) {
        int flag = userService.deleteUser(id);
        if (flag > 0) {
            return Result.OK();
        }else {
            return Result.FAIL();
        }
    }

    @DeleteMapping("/api/user")
    public Result deleteUsers( String ids) {
        if (StrUtil.isEmpty(ids)){
            throw new RuntimeException("请选择要删除的用户");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        int flag = userService.batchDeleteUser(idList);
        if (flag > 0) {
            return Result.OK();
        }else {
            return Result.FAIL();
        }
    }

    /**
     * 获取用户姓名。id
     * 活动
     */
    @GetMapping("api/owners")
    public Result getOwners(){
        List<OwnerVO> ownerVOList = userService.getOwners();
        return Result.OK(ownerVOList);
    }

}
